<?php


namespace App\Service\Admin;


use App\Constants\Redis\AdminCount;
use App\Dao\CooperativeDao;
use App\Utils\Mongo;
use App\Utils\Redis;
use Hyperf\Di\Annotation\Inject;

class StatisticsService extends BaseService
{
    /**
     * @var
     */
    protected $redis;

    /**
     * @Inject()
     * @var CooperativeDao
     */
    protected $cooperativeDao;

    public function __construct()
    {
       $this->redis = di(Redis::class);
    }

    /**
     * 获取统计数据
     * @return mixed
     */
    public function statisticsData()
    {
        //昨日新增会员数
        $data['user_count'] = intval($this->redis->get(AdminCount::YESTERDAY_ADD_USER));
        //昨日新增悬赏主
        $data['employer_count'] = intval($this->redis->get(AdminCount::YESTERDAY_ADD_EMPLOYER));
        //昨日新增合作商
        $data['cooperative_count'] = intval($this->redis->get(AdminCount::YESTERDAY_ADD_COOPERATIVE));
        //昨日成交佣金
        $data['commission_total'] = intval($this->redis->get(AdminCount::YESTERDAY_COMMISSION));
        //昨日悬赏主充值
        $data['recharge'] = intval($this->redis->get(AdminCount::YESTERDAY_EMPLOYER_RECHARGE));
        //昨日合作商收益
        $data['cooperative_profit'] = intval($this->redis->get(AdminCount::YESTERDAY_COOPERATIVE_PROFIT));
        //总用户数
        $data['user_total'] = intval($this->redis->get(AdminCount::USER_TOTAL));
        //总悬赏主数
        $data['employer_total'] = intval($this->redis->get(AdminCount::EMPLOYER_TOTAL));
        //总合作商数
        $data['cooperative_total'] = intval($this->redis->get(AdminCount::COOPERATIVE_TOTAL));

        return $data;
    }

    /**
     * @param $data
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function barChartData($data)
    {
        //默认7天
        $start_date = strtotime(date('Y-m-d 00:00:00',strtotime('-7 day')));
        $end_date = time();
        //天数
        if (isset($data['date_days']) && is_numeric($data['date_days'])){
            $days = (int)$data['date_days'] + 1;
            //开始时间日期
            $start_date = strtotime(date('Y-m-d 00:00:00',strtotime('-'.$days.' day')));
            //结束时间日期
            $end_date = strtotime(date('Y-m-d 23:59:59',strtotime('- 1 day')));
        }
        //自定义日期
        if (isset($data['start_date']) && isset($data['end_date'])){
            $start_date = strtotime(date('Y-m-d 00:00:00',strtotime($data['start_date'])));
            $end_date = strtotime(date('Y-m-d 23:59:59',strtotime($data['end_date'])));
        }
        $mgWhere = [
            '$and' => [
                ['date' => ['$gte'=>$start_date]],
                ['date' => ['$lte'=>$end_date]]
            ]
        ];

        $sort = ['sort' => ['created_at' => -1]];
        $result = [];
        //获取全部合作商下数据
        if (!isset($data['cooperative_id']) || empty($data['cooperative_id'])){
            $where['deleted_at'] = null;
            if (isset($data['province'])){
                $where['province'] = $data['province'];
            }
            if (isset($data['city'])){
                $where['city'] = $data['city'];
            }
            $coopers = $this->cooperativeDao->where($where)->pluck('id')->toArray();
            for ($i=0;$i < count($coopers);$i++){
                $dbKey = config('mongodb.default.db').'.barchart_'.$coopers[$i];
                array_push($result,$this->QueryDataToMg($dbKey,$mgWhere,$sort));
            }

            $dateExist = [];
            $list = [];
            foreach ($result as $key=>$item){
                foreach ($item as $k=>$val){
                    $date = date('Y-m-d',$val->date);
                    if(in_array($date,$dateExist)){
                        $list[$date]['count'] = $list[$date]['count'] + $val->cnt;
                    }else{
                        $list[$date]['count'] = $val->cnt;
                    }
                    array_push($dateExist,$date);
                    $list[$date]['date'] = $date;
                }
            }
            return array_values($list);
        }else{
            $dbKey = config('mongodb.default.db').'.barchart_'.$data['cooperative_id'];
            $result = $this->QueryDataToMg($dbKey,$mgWhere,$sort);
        }

        $existArr = [];
        $list = [];
        foreach ($result as $key=>$val){
            $date = $val->date ?? '';
            if (in_array($date,$existArr)){
                continue;
            }
            array_push($existArr,$date);
            $list[$key]['date'] = date('Y-m-d',$val->date??time());
            $list[$key]['count'] = $val->cnt ?? 0;
        }

        return $list;
    }

    /**
     * @param $dbKey
     * @param $where
     * @param $sort
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function QueryDataToMg($dbKey,$where,$sort)
    {
        return di(Mongo::class)->query($dbKey,$where,$sort);
    }

}